package org.jeecg.modules.messageReplies.controller;

import java.util.Arrays;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.messageReplies.entity.BlogMessageReplies;
import org.jeecg.modules.messageReplies.service.BlogMessageRepliesService;
import org.jeecg.config.shiro.IgnoreAuth;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: blog_message_replies
 * @Author: jeecg-boot
 * @Date: 2025-06-30
 * @Version: V1.0
 */
@Tag(name = "blog_message_replies")
@RestController
@RequestMapping("/blog/messageReplies")
@Slf4j
public class BlogMessageRepliesController extends JeecgController<BlogMessageReplies, BlogMessageRepliesService> {
    @Autowired
    private BlogMessageRepliesService blogMessageRepliesService;

    /**
     * 分页列表查询
     *
     * @param blogMessageReplies
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "blog_message_replies-分页列表查询")
    @Operation(summary = "blog_message_replies-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<BlogMessageReplies>> queryPageList(BlogMessageReplies blogMessageReplies,
                                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                           HttpServletRequest req) {
        QueryWrapper<BlogMessageReplies> queryWrapper = QueryGenerator.initQueryWrapper(blogMessageReplies, req.getParameterMap());
        Page<BlogMessageReplies> page = new Page<BlogMessageReplies>(pageNo, pageSize);
        IPage<BlogMessageReplies> pageList = blogMessageRepliesService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 公开的回复添加（无需权限）
     *
     * @param blogMessageReplies
     * @param request
     * @return
     */
    @Operation(summary = "公开的回复添加")
    @PostMapping(value = "/public/add")
    @IgnoreAuth
    public Result<String> addPublicReply(@RequestBody BlogMessageReplies blogMessageReplies, HttpServletRequest request) {
        // 设置默认状态为待审核
        blogMessageReplies.setStatus(0);
        // 设置IP地址
        blogMessageReplies.setIpAddress(getClientIpAddress(request));
        // 设置用户代理
        blogMessageReplies.setUserAgent(request.getHeader("User-Agent"));
        // 设置创建时间
        blogMessageReplies.setCreateTime(new Date());
        blogMessageRepliesService.save(blogMessageReplies);
        return Result.OK("回复提交成功，等待审核！");
    }

    /**
     * 公开的回复点赞（无需权限）
     *
     * @param id
     * @return
     */
    @Operation(summary = "公开的回复点赞")
    @PostMapping(value = "/public/like")
    @IgnoreAuth
    public Result<String> likeReply(@RequestParam(name = "id", required = true) String id) {
        BlogMessageReplies reply = blogMessageRepliesService.getById(id);
        if (reply == null) {
            return Result.error("回复不存在");
        }
        // 增加点赞数
        reply.setLikeCount(reply.getLikeCount() != null ? reply.getLikeCount() + 1 : 1);
        blogMessageRepliesService.updateById(reply);
        return Result.OK("点赞成功！");
    }

    /**
     * 添加
     *
     * @param blogMessageReplies
     * @return
     */
    @AutoLog(value = "blog_message_replies-添加")
    @Operation(summary = "blog_message_replies-添加")
    @RequiresPermissions("messageReplies:blog_message_replies:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody BlogMessageReplies blogMessageReplies) {
        blogMessageRepliesService.save(blogMessageReplies);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param blogMessageReplies
     * @return
     */
    @AutoLog(value = "blog_message_replies-编辑")
    @Operation(summary = "blog_message_replies-编辑")
    @RequiresPermissions("messageReplies:blog_message_replies:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody BlogMessageReplies blogMessageReplies) {
        blogMessageRepliesService.updateById(blogMessageReplies);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "blog_message_replies-通过id删除")
    @Operation(summary = "blog_message_replies-通过id删除")
    @RequiresPermissions("messageReplies:blog_message_replies:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        blogMessageRepliesService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "blog_message_replies-批量删除")
    @Operation(summary = "blog_message_replies-批量删除")
    @RequiresPermissions("messageReplies:blog_message_replies:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.blogMessageRepliesService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "blog_message_replies-通过id查询")
    @Operation(summary = "blog_message_replies-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<BlogMessageReplies> queryById(@RequestParam(name = "id", required = true) String id) {
        BlogMessageReplies blogMessageReplies = blogMessageRepliesService.getById(id);
        if (blogMessageReplies == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(blogMessageReplies);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param blogMessageReplies
     */
    @RequiresPermissions("messageReplies:blog_message_replies:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BlogMessageReplies blogMessageReplies) {
        return super.exportXls(request, blogMessageReplies, BlogMessageReplies.class, "blog_message_replies");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("messageReplies:blog_message_replies:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BlogMessageReplies.class);
    }

    /**
     * 获取客户端真实IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xip = request.getHeader("X-Real-IP");
        String xfor = request.getHeader("X-Forwarded-For");
        if (xfor != null && !xfor.isEmpty() && !"unKnown".equalsIgnoreCase(xfor)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = xfor.indexOf(",");
            if (index != -1) {
                return xfor.substring(0, index);
            } else {
                return xfor;
            }
        }
        xfor = xip;
        if (xfor != null && !xfor.isEmpty() && !"unKnown".equalsIgnoreCase(xfor)) {
            return xfor;
        }
        if (xfor == null || xfor.isEmpty() || "unknown".equalsIgnoreCase(xfor)) {
            xfor = request.getHeader("Proxy-Client-IP");
        }
        if (xfor == null || xfor.isEmpty() || "unknown".equalsIgnoreCase(xfor)) {
            xfor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (xfor == null || xfor.isEmpty() || "unknown".equalsIgnoreCase(xfor)) {
            xfor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (xfor == null || xfor.isEmpty() || "unknown".equalsIgnoreCase(xfor)) {
            xfor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (xfor == null || xfor.isEmpty() || "unknown".equalsIgnoreCase(xfor)) {
            xfor = request.getRemoteAddr();
        }
        return xfor;
    }

}
